<?php

include('SimpleImage.php');
include('func.php');

class Http {

    static public function getDomain() {
        return $_SERVER['HTTP_HOST'];
    }

    static public function getIp() {
        if (isset($_SERVER['HTTP_CLIENT_IP'])) {
            return $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            return $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            return $_SERVER['REMOTE_ADDR'];
        }
    }

    static public function isPost() {
        static $isPost = null;
        if (null === $isPost) {
            $isPost = ('POST' === $_SERVER['REQUEST_METHOD']);
        }
        return $isPost;
    }

    /**
     * @todo needs to enable WSDL caching after everything's done
     * @staticvar SoapClient $soap
     * @return SoapClient
     */
    static public function SOAPClient() {
        static $soap = null;
        if (null === $soap) {
            $soap = new SoapClient(Config::get('ws_url')/* , array(
                      'cache_wsdl' => WSDL_CACHE_MEMORY) */);
        }
        return $soap;
    }

    static public function UploadImage($FileControlName, $path, $iwidth='', &$picname = '') {
        static $result = '';
        $itype = $_FILES[$FileControlName]["type"];
        $isize = $_FILES[$FileControlName]["size"] / 1024;
        $itemp = $_FILES[$FileControlName]["tmp_name"];
        $iname = Date::getGmtTime() . str_replace('image/', '.', $itype);
        $picname = $iname;
        $ithum = str_replace('upload/', 'upload/thum', $iname);
        $iname = $path . $iname;
        if (($itype == "image/gif") || ($itype == "image/jpeg") || ($itype == "image/pjpeg") || ($itype == "image/png")) {
            if ($isize < 512) {
                move_uploaded_file($itemp, $iname);
                if (($iwidth != '') && (!notNum($iwidth, 'Size ')) && $iwidth > 0) {
                    $image = new SimpleImage();
                    $image->load($iname);
                    $image->resizeToWidth($iwidth);
                    $image->save(str_replace('upload/', 'upload/thum', $iname));
                }
            } else {
                $result = 'kích thước ảnh lớn hơn mức cho phép !';
            }
        } else {
            $result = 'Tập tin hình ảnh không hợp lệ !';
        }
        return $result;
    }

    static public function curPageURL() {
        $pageURL = 'http';
//        if ($_SERVER["HTTPS"] == "on") {
//            $pageURL .= "s";
//        }
        $pageURL .= "://";
        if ($_SERVER["SERVER_PORT"] != "80") {
            $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"];
        } else {
            $pageURL .= $_SERVER["SERVER_NAME"];
        }
        return $pageURL;
    }

}

